<template>
  <div class="page-scan-mana">
    <el-form :inline="true" :model="dataQueryForm" ref="dataQueryForm">
      <div class="pc-page-header">
        <el-form-item>
          <el-date-picker class="block"
                          v-model="dataQueryForm.marketDate"
                          type="daterange"
                          range-separator="-"
                          start-placeholder="行情开始日期"
                          end-placeholder="行情结束日期"
                          value-format="yyyy-MM-dd"
                          @change="getDate">
          </el-date-picker>
        </el-form-item>
        <el-form-item  prop="id">
          <el-select v-model="dataQueryForm.source" clearable placeholder="选择来源" class="pc-input3-col5" >
            <el-option v-for="item in sourceOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="id">
          <el-input v-model="dataQueryForm.uploadUser" clearable class="pc-input3-col5" placeholder="输入上传人"></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" @click="queryDataFn">搜索</el-button>
          <el-button type="primary" @click="refresh('dataQueryForm')">刷新</el-button>
          <el-button type="warning" @click="downloadTemplate()">下载模板</el-button>
        </el-form-item>
      </div>
    </el-form>

    <!--列表数据-->
    <egrid border class="page-list"
           :data="tableData"
           :columns="columns"
           :columns-schema="columnsSchema"
           :columns-props="columnsProps">
    </egrid>

    <!--分页组件-->
    <div class="pc-pagination-panel">
      <pc-pagination ref="pcPagination" :url="pageUrl.queryDataList" :queryData="dataQueryForm"
                     @on-query="queryCallBackFn">
      </pc-pagination>
    </div>

    <!--行情记录页面-->
    <pc-dialog-center :is-show="isShowDetailDialog" :title='dialogTitle' @on-close="isShowDetailDialog = false" width="1440" height="580">
      <div>
        <detail :marketId="marketId">
        </detail>
      </div>
    </pc-dialog-center>

    <!--Excel数据上传组件-->
    <upload-excel v-if="isShowExcelDialog" :apiUrl="apiUrl" :fileTypeName="fileTypeName"
                  @success="afterUploadExcel" @close="isShowExcelDialog = false;">
    </upload-excel>

  </div>
</template>

<script type="text/ecmascript-6">
  import PcPagination from 'components/form/pagination';
  import PcButton from 'components/form/button';
  import PcDialogCenter from 'components/dialog/center.vue';
  import EgridCellView from 'components/wms/comm/EgridCellView.vue';
  import Detail from './detail.vue';
  import {enums} from '../../../../utils/settings';
  import UploadExcel from 'components/fileUpload/uploadExcel.vue';
  let that;

  // 标题链接详情
  var marketDateLink = {
    template: ` <el-button class="base-market-no" @click="viewdetail(row)" type="text" size="small">{{this.row.marketDate}}</el-button>`,
    props: ['row'],
    methods: {
      viewdetail(val) {
        this.$emit('view-detail', val);
      }
    }
  };

  // 操作按钮
  var Btn = {
    template: `<div style="display:flex; width: 100%;flex-wrap: wrap">
        <el-button type="primary" plain @click="gotoEditMarket(row)">更新</el-button>
        <el-button type="warning" plain @click="gotoDownloadMarket(row)">下载</el-button>
        <el-button v-if="showRevertBtn" type="info" plain @click="gotoRevertMarket(row)">重置</el-button>
      </div>`,
    props: ['row'],
    computed: {
      // 是否显示重置按钮
      showRevertBtn() {
        return this.row.source === enums.SK_MARKET_SOURCE_TYPE.USER_UPLOAD;
      }
    },
    methods: {
      // 跳转编辑行情
      gotoEditMarket (val) {
        this.$emit('edit-market', val);
      },
      // 跳转下载行情
      gotoDownloadMarket (val) {
        this.$emit('download-market', val);
      },
      // 跳转重置行情
      gotoRevertMarket (val) {
        this.$emit('revert-market', val);
      }
    }
  };

  export default {
    data() {
      return {
        marketId: null,
        dialogTitle: null,
        isShowDetailDialog: false,
        isShowExcelDialog: false,
        apiUrl: '',
        fileTypeName: null,
        dataQueryForm: {
          marketDate: null,
          startDate: null,
          endDate: null,
          source: null,
          uploadUser: null
        },
        tableData: [],
        columns: [
          {
            label: '行情日期',
            // prop: 'marketDate'
            component: marketDateLink,
            listeners: {
              'view-detail' (val) {
                that.viewDetailFn(val);
              }
            }
          },
          {
            label: '来源',
            prop: 'sourceDisplay'
          },
          {
            label: '上传人',
            prop: 'uploadUser'
          },
          {
            label: '上传时间',
            prop: 'uploadTime'
          },
          {
            label: '操作',
            minWidth: 120,
            fixed: 'right',
            component: Btn, // 'el-button'
            listeners: {
              'edit-market' (data) {
                that.showExcelDialog(data);
              },
              'download-market' (data) {
                that.downloadMarketFn(data);
              },
              'revert-market' (data) {
                that.revertMarketFn(data);
              }
            },
            propsHandler: function ({ row, col, column }) {
              return {row, col, column};
            }
          }
        ],
        columnsSchema: {
        },
        selecetedRows: [],
        // columnsProps 用于定义所有 columns 公共的属性，
        // 这里属性可以参考这里： http://element.eleme.io/#/zh-CN/component/table#table-column-attributes
        columnsProps: {
          height: 40,
          minWidth: 140,
          showOverflowTooltip: true,
          component: EgridCellView
        },
        sourceOption: [
          {
            value: 1,
            label: '前一天行情'
          }, {
            value: 2,
            label: '用户上传'
          }
        ],
        // columnsHandler 可用于在现有的 columns 进行操作，对 columns 进行增删改，这里新增了操作列
        pageUrl: {
          queryDataList: '/malisk/server/market/queryMarketList'
        }
      };
    },
    components: {
      PcPagination, PcButton, PcDialogCenter, Detail, UploadExcel
    },
    created() {
      that = this;
    },

    methods: {
      getDate() {
        if (this.dataQueryForm.marketDate === null) {
          this.dataQueryForm.startDate = '';
          this.dataQueryForm.endDate = '';
        } else {
          this.dataQueryForm.startDate = this.dataQueryForm.marketDate[0];
          this.dataQueryForm.endDate = this.dataQueryForm.marketDate[1];
        }
      },
      showExcelDialog(scopeRow) {
        this.apiUrl = process.env.API_ROOT + 'malisk/server/market/importMarketDetailList/' + scopeRow.marketDate + '/' + scopeRow.version;
        this.fileTypeName = '行情数据（行情日期：' + scopeRow.marketDate + '）';
        this.isShowExcelDialog = true;
      },
      afterUploadExcel() {
        this.isShowExcelDialog = false;
        this.queryDataFn();
      },
      // 表头样式
      getHeaderStyle({row, column, rowIndex, columnIndex}) {
        if (rowIndex === 0) {
          return 'background: #f5f5f5; height: 50px';
        } else {
          return '';
        }
      },
      getRowClass({row, column, rowIndex, columnIndex}) {
        if (rowIndex === 0) {
          return 'background:rgb(245, 245, 245);';
        } else {
          return '';
        }
      },
      viewDetailFn (scopeRow) {
        this.marketId = scopeRow.id;
        this.dialogTitle = '行情记录（行情日期：' + scopeRow.marketDate + '）';
        this.isShowDetailDialog = true;
      },
      downloadTemplate () {
        this.exportFile({type: 'POST',
          url: '/malisk/server/market/downloadTemplateForMarket',
          data: {},
          loading: true,
          fileNameStart: '市场行情（行情日期：YYYY-MM-DD）'
        });
      },
      downloadMarketFn (scopeRow) {
        this.exportFile({type: 'POST',
          url: '/malisk/server/market/exportMarketDetailList',
          data: {marketId: scopeRow.id},
          loading: true,
          fileNameStart: '市场行情（行情日期：' + scopeRow.marketDate + '）'
        });
      },
      revertMarketFn (val) {
        // 调用后端接口
        this.ajaxBox({
          title: '操作确认',
          message: '是否重置到最初的版本？',
          type: 'POST',
          url: '/malisk/server/market/revertMarket',
          data: {
            marketDate: val.marketDate,
            version: val.version
          },
          loading: true,
          success: (res) => {
            setTimeout(() => {
              this.$pcNProgress.done();
            }, 300);
            if (res.code === 200) {
              this.successTip('重置成功', 2000);
              this.$refs.pcPagination.queryListWithPageFn(false);
            } else {
              this.errorTip(res.message);
            }
          }
        });
      },
      openMessage() {
        this.$notify.info({
          title: '自定义位置',
          message: '右下角弹出的消息',
          position: 'bottom-right'
        });
      },
      queryCallBackFn(res) {
        this.tableData = res.result.list;
      },
      queryDataFn() {
        this.$refs.pcPagination.queryListWithPageFn(true);
      },
      refresh(formName) {
        this.$refs[formName].resetFields();
        this.dataQueryForm.marketDate = null;
        this.dataQueryForm.startDate = null;
        this.dataQueryForm.endDate = null;
        this.dataQueryForm.source = null;
        this.dataQueryForm.uploadUser = null;
        this.queryDataFn();
      }
    }
  };
</script>
<style>
  .base-market-no {
    padding: 5px 0px !important;
  }
</style>
